package nccloud.web.ic.invcount.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import nc.bs.framework.common.NCLocator;
import nc.itf.ic.m4r.IInvCountOnhand;
import nc.itf.uap.IUAPQueryBS;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.pubitf.ic.mstoreadmin.IStoreadminQueryService;
import nc.pubitf.ic.onhand.IOnhandQry;
import nc.vo.ic.admin.ICModuleManager;
import nc.vo.ic.m4r.define.CountTypeChooserCond;
import nc.vo.ic.m4r.entity.InvCountBillVO;
import nc.vo.ic.m4r.entity.InvCountBodyVO;
import nc.vo.ic.m4r.entity.InvCountHeaderVO;
import nc.vo.ic.m4r.enumerate.InvCountMode;
import nc.vo.ic.material.define.InvWarehouseVO;
import nc.vo.ic.onhand.entity.OnhandVO;
import nc.vo.ic.onhand.pub.OnhandQryCond;
import nc.vo.ic.onhand.pub.OnhandVOTools;
import nc.vo.ic.pub.sql.SqlUtil;
import nc.vo.ic.pub.util.CollectionUtils;
import nc.vo.ic.pub.util.StringUtil;
import nc.vo.ic.pub.util.VOEntityUtil;
import nc.vo.ic.pub.util.ValueCheckUtil;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.pub.BusinessException;
import nc.vo.pub.CircularlyAccessibleValueObject;
import nc.vo.pub.SuperVO;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.pattern.data.ValueUtils;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.pubapp.pattern.pub.MapList;
import nc.vo.pubapp.util.VORowNoUtils;
import nc.vo.scmf.ic.mbatchcode.BatchcodeVO;
import nccloud.framework.core.json.IJson;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.action.itf.ICommonAction;
import nccloud.framework.web.container.ClientInfo;
import nccloud.framework.web.container.IRequest;
import nccloud.framework.web.container.SessionContext;
import nccloud.framework.web.convert.translate.Translator;
import nccloud.framework.web.json.JsonFactory;
import nccloud.framework.web.processor.template.BillCardConvertProcessor;
import nccloud.framework.web.ui.pattern.billcard.BillCard;
import nccloud.pubitf.ic.invcount.service.IInvcoutService;
import nccloud.pubitf.ic.onhand.service.ISupplierAndCustomerService;
import nccloud.pubitf.ic.pub.service.IOrgInfoQueryService;
import nccloud.web.ic.invcount.entity.InvcountChooseInfoDTO;
import nccloud.web.ic.pub.utils.DealDisplayIsNullUtil;

public class InvcountChooseAction implements ICommonAction {
	
	private IUAPQueryBS ibs;
	
	private IUAPQueryBS getIbs() {
		if(ibs == null) {
			ibs = NCLocator.getInstance().lookup(IUAPQueryBS.class);
		}
		return ibs;
	}
	
	public Object doAction(IRequest request) {
		String str = request.read();
		IJson json = JsonFactory.create();
		InvcountChooseInfoDTO info = (InvcountChooseInfoDTO) json.fromJson(str, InvcountChooseInfoDTO.class);
		CountTypeChooserCond cond = this.getCond(info);
		int invCountMode = cond.getInvMode();
		String pk_org = cond.getPk_org();
		String whid = cond.getInvWh();
		UFDate invDate = cond.getInvdate();
		UFDate nowDate = new UFDate(SessionContext.getInstance().getClientInfo().getBizDateTime());
		OnhandVO[] onhandVOs = new OnhandVO[0];
		StringBuilder where;
		if (invDate.isSameDate(nowDate) && cond.getIntDay() <= 0) {
			OnhandQryCond queryHandCond = this.getWhereByParam(cond);
			if (invCountMode == (Integer) InvCountMode.WHOLE_STORE.value()) {
				this.setCmaterialvidCondByParam(queryHandCond, cond);
			} else if (invCountMode == (Integer) InvCountMode.LOCATION.value()) {
				if (ValueCheckUtil.isNullORZeroLength(cond.getAlSpacesc())) {
					ExceptionUtils.wrappBusinessException(
							NCLangRes4VoTransl.getNCLangRes().getStrByID("4008012_0", "04008012-0006"));
				}

				this.setCmaterialvidCondByParam(queryHandCond, cond);
				queryHandCond.setClocationids((String[]) cond.getAlSpacesc().toArray(new String[0]));
			} else if (invCountMode != (Integer) InvCountMode.MATERIAL.value()
					&& invCountMode != (Integer) InvCountMode.MATERIAL_CLASS.value()) {
				if (invCountMode == (Integer) InvCountMode.CYCLE.value()) {
					this.setCmaterialvidCondByParam(queryHandCond, cond);
				} else if (invCountMode == (Integer) InvCountMode.STORE_KEEPER.value()) {
					try {
						this.storeKeeperCount(cond, queryHandCond);
					} catch (BusinessException var17) {
						ExceptionUtils.wrappException(var17);
					}
				} else if (invCountMode == (Integer) InvCountMode.NEGATIVE_ONHAND.value()) {
					this.setCmaterialvidCondByParam(queryHandCond, cond);
					where = new StringBuilder();
					where.append(SqlUtil.getFun_COALESCE("ic_onhandnum.nonhandnum", "0"));
					where.append(" <0 ");
					this.addWhere(queryHandCond, where.toString());
				} else if (invCountMode == (Integer) InvCountMode.GUARANTEE_PERIOD.value()) {
					this.setCmaterialvidCondByParam(queryHandCond, cond);
					this.addWhere(queryHandCond, this.getDvalidateWhere(cond.getInvdate(), cond.getCountDay(), pk_org));
				} else if (invCountMode != (Integer) InvCountMode.NACTIVE.value()
						&& invCountMode == (Integer) InvCountMode.DYNAMIC.value()) {
					String[] cmaterialvids = this.getCmaterial(cond, cond.getCountDay());
					if (ValueCheckUtil.isNullORZeroLength(cmaterialvids)) {
						return null;
					}

					queryHandCond.setCmaterialvids(cmaterialvids);
				}
			} else {
				this.invCount(cond, queryHandCond);
			}

			onhandVOs = this.getOnhandNum(queryHandCond);
		} else {
			if (invCountMode == (Integer) InvCountMode.LOCATION.value()) {
				if (ValueCheckUtil.isNullORZeroLength(cond.getAlSpacesc())) {
					ExceptionUtils.wrappBusinessException(
							NCLangRes4VoTransl.getNCLangRes().getStrByID("4008012_0", "04008012-0006"));
				}
			} else if (invCountMode == (Integer) InvCountMode.MATERIAL.value()) {
				int invType = cond.getInvType();
				if (invType == 0 && ValueCheckUtil.isNullORZeroLength(cond.getAlInvid())) {
					ExceptionUtils.wrappBusinessException(
							NCLangRes4VoTransl.getNCLangRes().getStrByID("4008012_0", "04008012-0009"));
				}

				if (ValueCheckUtil.isNullORZeroLength(cond.getAlInvid())) {
					ExceptionUtils.wrappBusinessException(
							NCLangRes4VoTransl.getNCLangRes().getStrByID("4008012_0", "04008012-0010"));
				}
			}

			try {
				onhandVOs = ((IInvCountOnhand) ServiceLocator.find(IInvCountOnhand.class)).getOnhandVOForInvdate(cond);
			} catch (BusinessException var16) {
				ExceptionUtils.wrappException(var16);
			}

			if (!cond.getZeroOnhand()) {
				onhandVOs = OnhandVOTools.filterOnhandVONumZero(onhandVOs);
			}
		}

		if (ValueCheckUtil.isNullORZeroLength(onhandVOs)) {
			return null;
		} else {
			if (invCountMode == (Integer) InvCountMode.NACTIVE.value()) {
				String[] cmaterials = this.getCmaterial(cond, cond.getCountDay());
				onhandVOs = this.nactiveCount(cmaterials, onhandVOs);
			}

			if (invCountMode == (Integer) InvCountMode.CYCLE.value()) {
				onhandVOs = this.cycleCount(whid, onhandVOs);
			}

			if (ValueCheckUtil.isNullORZeroLength(onhandVOs)) {
				return null;
			} else {
				InvCountBillVO aggVO = this.getInvCount(pk_org, whid, onhandVOs, cond.getBarcode(), cond.getInvdate());
				//20231020 add by crt 将单价、金额、上次盘点时间分别记录在表体自定义项1、2、3。
				//将aggvo中的物料、仓库进行匹配，看是否曾经盘点过如有，将上次盘点单的盘点日期填入表体自定义项1
				String ck = aggVO.getHead().getCwarehouseid();
				List<String> mpks= new ArrayList<String>();
				InvCountBodyVO[] bvos = aggVO.getBodys();
				for (InvCountBodyVO bvo : bvos) {
					mpks.add(bvo.getCmaterialoid());
				}
				if(mpks.size()>0) {
					//上次盘点时间
					StringBuffer sb = new StringBuffer();
					sb.append("SELECT b.cmaterialoid wl,max(h.dcountdate) rq FROM ic_invcount_b b ") 
					.append("LEFT JOIN ic_invcount_h h on h.cspecialhid = b.cspecialhid ")
					.append("WHERE nvl(h.dr,0)=0 AND nvl(h.dr,0)=0 AND h.pk_org ='"+pk_org+"' AND h.cwarehouseid='"+ck+"' AND b.cmaterialoid IN (");
					for (int i = 0; i < mpks.size(); i++) {
						sb.append("'"+mpks.get(i)+"',");
					}
					sb.deleteCharAt(sb.length()-1).append(") GROUP BY b.cmaterialoid");
					try {
						List<Map<String,String>> datalist = (List<Map<String, String>>) getIbs().executeQuery(sb.toString(), new MapListProcessor());
						if(datalist.size()>0) {
							// key 物料pk，value 最后盘点时间
							Map<String,String> datemap = new HashMap<String,String>();
							for (Map<String, String> map : datalist) {
								datemap.put(map.get("wl"), map.get("rq"));
							}
							// 循环bvos 把所有盘点时间填入自定义1
							for (int i = 0; i < bvos.length; i++) {
								String rq = datemap.get(bvos[i].getCmaterialoid());
								if(rq!=null) {
									bvos[i].setVbdef1(rq);
								}
							}
						}
					} catch (BusinessException e) {
						ExceptionUtils.wrappBusinessException("查询上次盘点时间出错，请重试。");
					}
					//	单价、金额
					StringBuffer sb1 = new StringBuffer();
					sb1.append("SELECT cinventoryid,nprice,max(ts) ts FROM ") 
						.append("(SELECT cinventoryid,CASE WHEN fpricemodeflag = 5 OR fpricemodeflag = 7 THEN nplanedprice ELSE nprice END nprice,ts ") 
						.append(" FROM ia_detailledger ")
						.append(" WHERE pk_org = '"+pk_org+"' ")
						.append(" AND pk_group = '"+SessionContext.getInstance().getClientInfo().getPk_group()+"' ")
						.append(" AND dr = 0 AND cinventoryid IN (");
					for (int i = 0; i < mpks.size(); i++) {
						sb1.append("'"+mpks.get(i)+"',");
					} 
					sb1.deleteCharAt(sb1.length()-1).append(")) GROUP BY cinventoryid,nprice ORDER BY ts asc");
					try {
						List<Map<String,String>> pricelist = (List<Map<String, String>>) getIbs().executeQuery(sb1.toString(), new MapListProcessor());
						// key 物料pk，单价nprice
						Map<String,String> pricemap = new HashMap<String,String>();
						for (Map<String, String> map : pricelist) {
							pricemap.put(map.get("cinventoryid"), map.get("nprice"));
						}
						//	循环bvos 把单价和金额放入vbdef2.3
						
						for (int i = 0; i < bvos.length; i++) {
							String nprice = pricemap.get(bvos[i].getCmaterialoid());
							if(nprice!=null) {
								bvos[i].setVbdef2(nprice);
								UFDouble nnum = bvos[i].getNnum();
								bvos[i].setVbdef3(new UFDouble(nprice).multiply(nnum).toString());
							}
						}
					} catch (BusinessException e) {
						ExceptionUtils.wrappBusinessException("查询单价金额出错，请重试。");
					}
				}
				where = null;
				BillCardConvertProcessor processor = new BillCardConvertProcessor();
				BillCard retcard = processor.convert(info.getPageid(), aggVO);
				DealDisplayIsNullUtil.dealBillCardDisPlayIsNull(new String[]{"vbatchcode"}, retcard);
				DealDisplayIsNullUtil.dealVbatchcodeRelation(retcard, false);
				Translator translator = new Translator();
				translator.translate(retcard);
				return retcard;
			}
		}
	}

	private CountTypeChooserCond getCond(InvcountChooseInfoDTO info) {
		CountTypeChooserCond cond = new CountTypeChooserCond();
		cond.setInvdate(info.getInvdate());
		cond.setInvWh(info.getInvWh());
		cond.setPk_org(info.getPk_org());
		cond.setInvMode(Integer.parseInt(info.getInvMode()));
		cond.setAlSpacesc(info.getAlSpacesc());
		cond.setZeroOnhand("0".equals(info.getZeroOnhand()));
		if ("1".equals(info.getZeroOnhand())) {
			cond.setIntDay(Integer.parseInt(info.getIntDay()));
		}

		if (null != info.getInvType() && !"".equals(info.getInvType())) {
			cond.setInvType(Integer.parseInt(info.getInvType()));
		}

		cond.setAlInvid(info.getAlInvid());
		cond.setStrManager(info.getStrManager());
		String var3 = info.getInvMode();
		byte var4 = -1;
		switch (var3.hashCode()) {
			case 54 :
				if (var3.equals("6")) {
					var4 = 0;
				}
				break;
			case 55 :
				if (var3.equals("7")) {
					var4 = 1;
				}
			case 56 :
			default :
				break;
			case 57 :
				if (var3.equals("9")) {
					var4 = 2;
				}
		}

		switch (var4) {
			case 0 :
				cond.setCountDay(Integer.parseInt(info.getDynamicDay()));
				break;
			case 1 :
				cond.setCountDay(Integer.parseInt(info.getShelfLifeDay()));
				break;
			case 2 :
				cond.setCountDay(Integer.parseInt(info.getNoDynamicDay()));
		}

		return cond;
	}

	private OnhandQryCond getWhereByParam(CountTypeChooserCond cond) {
		OnhandQryCond onhandQryCond = new OnhandQryCond();
		onhandQryCond.addAllSelectFields();
		onhandQryCond.setISSum(true);
		onhandQryCond.addSelectFields(new String[]{"pk_onhanddim"});
		StringBuilder sbSelFields = new StringBuilder();
		sbSelFields.append("handdim.").append("cwarehouseid").append("='").append(cond.getInvWh()).append("' AND ");
		sbSelFields.append("handdim.").append("pk_org").append("='").append(cond.getPk_org()).append("' ");
		if (!cond.getZeroOnhand()) {
			sbSelFields.append(" AND (").append("ic_onhandnum").append(".nonhandnum <> 0 or ").append("ic_onhandnum")
					.append(".nonhandastnum <> 0 ) ");
		}

		onhandQryCond.setWhere(sbSelFields.toString());
		onhandQryCond.setBinnerWhere(true);
		return onhandQryCond;
	}

	private void setCmaterialvidCondByParam(OnhandQryCond queryHandCond, CountTypeChooserCond cond) {
		if (cond.getIntDay() > 0) {
			String[] cmaterialvids = this.getCmaterial(cond, cond.getIntDay());
			queryHandCond.setCmaterialvids(cmaterialvids);
		}

	}

	private String[] getCmaterial(CountTypeChooserCond cond, int days) {
		if (days < 0) {
			return null;
		} else {
			UFDate dnow = cond.getInvdate();
			UFDate dbef = dnow.getDateBefore(days);
			IInvcoutService service = (IInvcoutService) ServiceLocator.find(IInvcoutService.class);
			return service.getCmaterial(dbef, dnow, cond);
		}
	}

	private void invCount(CountTypeChooserCond cond, OnhandQryCond queryHandCond) {
		StringBuffer where = new StringBuffer();
		int invType = cond.getInvType();
		String[] cmaterialvids = this.getCmaterial(cond, cond.getIntDay());
		if (invType == 0) {
			if (ValueCheckUtil.isNullORZeroLength(cond.getAlInvid())) {
				ExceptionUtils.wrappBusinessException(
						NCLangRes4VoTransl.getNCLangRes().getStrByID("4008012_0", "04008012-0009"));
			}

			queryHandCond.setPk_materialclasses((String[]) cond.getAlInvid().toArray(new String[0]));
			this.addWhere(queryHandCond, where.toString());
			queryHandCond.setCmaterialvids(cmaterialvids);
		} else {
			if (ValueCheckUtil.isNullORZeroLength(cond.getAlInvid())) {
				ExceptionUtils.wrappBusinessException(
						NCLangRes4VoTransl.getNCLangRes().getStrByID("4008012_0", "04008012-0010"));
			}

			if (ValueCheckUtil.isNullORZeroLength(cmaterialvids)) {
				queryHandCond.setCmaterialvids((String[]) cond.getAlInvid().toArray(new String[0]));
			} else {
				Set<String> cmaterialset = new HashSet();
				CollectionUtils.addArrayToSet(cmaterialset, cmaterialvids);
				List<String> lvids = new ArrayList();
				Iterator var8 = cond.getAlInvid().iterator();

				while (var8.hasNext()) {
					String vid = (String) var8.next();
					if (cmaterialset.contains(vid)) {
						lvids.add(vid);
					}
				}

				if (lvids.size() > 0) {
					queryHandCond.setCmaterialvids((String[]) lvids.toArray(new String[0]));
				}
			}

		}
	}

	private void addWhere(OnhandQryCond cond, String where) {
		if (!StringUtil.isSEmptyOrNull(where)) {
			cond.setWhere(SqlUtil.andTowWhere(cond.getWhere(), where));
		}
	}

	private void storeKeeperCount(CountTypeChooserCond cond, OnhandQryCond queryHandCond) throws BusinessException {
		String pk_org = cond.getPk_org();
		String whid = cond.getInvWh();
		String storeKeeper = cond.getStrManager();
		IStoreadminQueryService service = (IStoreadminQueryService) ServiceLocator.find(IStoreadminQueryService.class);
		IOrgInfoQueryService orgInfo = (IOrgInfoQueryService) ServiceLocator.find(IOrgInfoQueryService.class);
		MapList<String, String> map = service.getCmaterialByWarehouseManager(orgInfo.getPk_corp(pk_org),
				new String[]{whid}, storeKeeper, (String[]) null);
		if (map != null && map.containsKey(whid)) {
			this.setCmaterialvidCondByParam(queryHandCond, cond);
			String[] ids = (String[]) CollectionUtils.listToArray(map.get(whid));
			if (!ValueCheckUtil.isNullORZeroLength(ids)) {
				this.setFilterDim(queryHandCond, "cmaterialoid", ids);
			}

		} else {
			ExceptionUtils
					.wrappBusinessException(NCLangRes4VoTransl.getNCLangRes().getStrByID("4008012_0", "04008012-0011"));
		}
	}

	private void setFilterDim(OnhandQryCond cond, String field, String[] values) {
		if (!ValueCheckUtil.isNullORZeroLength(values)) {
			String[] fields = new String[]{field};
			String[] var5 = values;
			int var6 = values.length;

			for (int var7 = 0; var7 < var6; ++var7) {
				String value = var5[var7];
				cond.addFilterDimConditon(fields, new Object[]{value});
			}

		}
	}

	private String getDvalidateWhere(UFDate dnow, int sDay, String pk_org) {
		StringBuffer sql = new StringBuffer();
		UFDate dafter = dnow.getDateAfter(sDay);
		String batchtable = (new BatchcodeVO()).getMetaData().getPrimaryAttribute().getColumn().getTable().getName();
		sql.append(" " + batchtable + "." + "dvalidate" + ">='" + dnow + "' AND " + batchtable + "." + "dvalidate"
				+ "<='" + dafter + "' ");
		return sql.toString();
	}

	private OnhandVO[] getOnhandNum(OnhandQryCond onhandQryCond) {
		try {
			OnhandVO[] onhandVOs = ((IOnhandQry) ServiceLocator.find(IOnhandQry.class)).queryOnhand(onhandQryCond);
			return ValueCheckUtil.isNullORZeroLength(onhandVOs) ? null : onhandVOs;
		} catch (BusinessException var3) {
			ExceptionUtils.wrappException(var3);
			return null;
		}
	}

	private OnhandVO[] nactiveCount(String[] cmaterials, OnhandVO[] onhandVOs) {
		if (ValueCheckUtil.isNullORZeroLength(cmaterials)) {
			return onhandVOs;
		} else {
			List<OnhandVO> list = new ArrayList();
			Set<String> set = new HashSet();
			CollectionUtils.addArrayToSet(set, cmaterials);
			OnhandVO[] var5 = onhandVOs;
			int var6 = onhandVOs.length;

			for (int var7 = 0; var7 < var6; ++var7) {
				OnhandVO onhandVO = var5[var7];
				if (!set.contains(onhandVO.getCmaterialvid())) {
					list.add(onhandVO);
				}
			}

			return (OnhandVO[]) CollectionUtils.listToArray(list);
		}
	}

	private OnhandVO[] cycleCount(String cwarehouseid, OnhandVO[] onhandVOs) {
		if (ValueCheckUtil.isNullORZeroLength(onhandVOs)) {
			return null;
		} else {
			String[] vids = VOEntityUtil.getVOsNotRepeatValue(onhandVOs, "cmaterialvid");
			List<OnhandVO> list = new ArrayList();
			Map<String, InvWarehouseVO> map = this.getInvWarehousefo(cwarehouseid, vids);
			if (ValueCheckUtil.isNullORZeroLength(map)) {
				return null;
			} else {
				List<String> listMapKey = new ArrayList();
				Iterator var7 = map.entrySet().iterator();

				while (var7.hasNext()) {
					Entry<String, InvWarehouseVO> entry = (Entry) var7.next();
					if (ValueUtils.getInt(((InvWarehouseVO) entry.getValue()).getCountperiod()) > this
							.getCountperiod(((InvWarehouseVO) entry.getValue()).getLastcounttime())) {
						listMapKey.add(entry.getKey());
					}
				}

				var7 = listMapKey.iterator();

				while (var7.hasNext()) {
					String mapKey = (String) var7.next();
					map.remove(mapKey);
				}

				OnhandVO[] var11 = onhandVOs;
				int var13 = onhandVOs.length;

				for (int var9 = 0; var9 < var13; ++var9) {
					OnhandVO vo = var11[var9];
					if (map.keySet().contains(vo.getCmaterialvid())) {
						list.add(vo);
					}
				}

				return (OnhandVO[]) CollectionUtils.listToArray(list);
			}
		}
	}

	private Map<String, InvWarehouseVO> getInvWarehousefo(String cwarehouseid, String[] cinv_vids) {
		IInvcoutService service = (IInvcoutService) ServiceLocator.find(IInvcoutService.class);
		InvWarehouseVO[] vos = service.getInvWarehouseVO(cwarehouseid, cinv_vids);
		if (ValueCheckUtil.isNullORZeroLength(vos)) {
			return null;
		} else {
			Map<String, InvWarehouseVO> map = new HashMap();
			InvWarehouseVO[] var6 = vos;
			int var7 = vos.length;

			for (int var8 = 0; var8 < var7; ++var8) {
				InvWarehouseVO vo = var6[var8];
				if (vo != null) {
					map.put(vo.getPk_material(), vo);
				}
			}

			return map;
		}
	}

	private int getCountperiod(UFDate lastcounttime) {
		ClientInfo context = SessionContext.getInstance().getClientInfo();
		UFDate sLogDate = new UFDate(context.getBizDateTime());
		UFDate sStartDate = (new ICModuleManager()).getICModuleEnableDate(context.getPk_group());
		if (lastcounttime == null) {
			return sStartDate == null ? -1 : sLogDate.getDaysAfter(sStartDate);
		} else {
			return sLogDate.getDaysAfter(lastcounttime);
		}
	}

	private InvCountBillVO getInvCount(String pk_org, String cwarehouseid, OnhandVO[] onhandVOs, boolean barcode,
			UFDate dnow) {
		InvCountHeaderVO headvo = this.fillHeadInfo(pk_org, dnow);
		headvo.setCwarehouseid(cwarehouseid);
		List<InvCountBodyVO> list = this.getInvCountBodyVO(pk_org, onhandVOs, barcode);
		VORowNoUtils.setVOsRowNoByRule((CircularlyAccessibleValueObject[]) CollectionUtils.listToArray(list), "crowno");
		InvCountBillVO currVOs = new InvCountBillVO();
		currVOs.setParentVO(headvo);
		currVOs.setChildrenVO((CircularlyAccessibleValueObject[]) CollectionUtils.listToArray(list));
		return currVOs;
	}

	private InvCountHeaderVO fillHeadInfo(String pk_org, UFDate dnow) {
		InvCountHeaderVO headvo = new InvCountHeaderVO();
		headvo.setPk_org(pk_org);
		IOrgInfoQueryService orgInfo = (IOrgInfoQueryService) ServiceLocator.find(IOrgInfoQueryService.class);
		headvo.setPk_org_v(orgInfo.getPk_org_v(pk_org).getPk_vid());
		headvo.setCorpoid(orgInfo.getPk_corp(pk_org));
		headvo.setCorpvid(orgInfo.getPk_corp_v(pk_org));
		headvo.setPk_group(SessionContext.getInstance().getClientInfo().getPk_group());
		headvo.setFbillflag(1);
		headvo.setDbilldate(new UFDate(SessionContext.getInstance().getClientInfo().getBizDateTime()));
		headvo.setDcountdate(dnow);
		return headvo;
	}

	private List<InvCountBodyVO> getInvCountBodyVO(String pk_org, OnhandVO[] onhandVOs, boolean barcode) {
		IInvcoutService service = (IInvcoutService) ServiceLocator.find(IInvcoutService.class);
		new ArrayList();
		List<InvCountBodyVO> list = service.getList(pk_org, onhandVOs, barcode);
		if (list != null && list.size() > 0) {
			Set<String> customeridSet = new HashSet();
			Set<String> customervidSet = new HashSet();
			Set<String> supplieridSet = new HashSet();
			Set<String> suppliervidSet = new HashSet();
			Iterator var10 = list.iterator();

			while (var10.hasNext()) {
				InvCountBodyVO body = (InvCountBodyVO) var10.next();
				this.setSetValue(customeridSet, customervidSet, body.getCasscustid(), body.getCasscustvid());
				this.setSetValue(supplieridSet, suppliervidSet, body.getCvendorid(), body.getCvendorvid());
				this.setSetValue(supplieridSet, supplieridSet, body.getCvmivenderid(), body.getCvmivendervid());
				this.setSetValue(customeridSet, customervidSet, body.getCtplcustomerid(), body.getCtplcustomervid());
			}

			Map<String, String> customeridMap = null;
			Map<String, String> customervidMap = null;
			Map<String, String> supplieridMap = null;
			Map<String, String> suppliervidMap = null;
			ISupplierAndCustomerService supplierAndCustomerService = (ISupplierAndCustomerService) ServiceLocator
					.find(ISupplierAndCustomerService.class);
			if (!customeridSet.isEmpty()) {
				customeridMap = supplierAndCustomerService
						.queryCustomerVidsByOids((String[]) CollectionUtils.setToArray(customeridSet));
			}

			if (!customervidSet.isEmpty()) {
				customervidMap = supplierAndCustomerService
						.queryCustomerOidsByVids((String[]) CollectionUtils.setToArray(customervidSet));
			}

			if (!supplieridSet.isEmpty()) {
				supplieridMap = supplierAndCustomerService
						.querySupplierVidsByOids((String[]) CollectionUtils.setToArray(supplieridSet));
			}

			if (!suppliervidSet.isEmpty()) {
				suppliervidMap = supplierAndCustomerService
						.querySupplierOidsByVids((String[]) CollectionUtils.setToArray(suppliervidSet));
			}

			Iterator var15 = list.iterator();

			while (var15.hasNext()) {
				InvCountBodyVO body = (InvCountBodyVO) var15.next();
				this.setVO(body, body.getCasscustid(), body.getCasscustvid(), "casscustid", "casscustvid",
						customeridMap, customervidMap);
				this.setVO(body, body.getCvendorid(), body.getCvendorvid(), "cvendorid", "cvendorvid", supplieridMap,
						suppliervidMap);
				this.setVO(body, body.getCvmivenderid(), body.getCvmivendervid(), "cvmivenderid", "cvmivendervid",
						supplieridMap, suppliervidMap);
				this.setVO(body, body.getCtplcustomerid(), body.getCtplcustomervid(), "ctplcustomerid",
						"ctplcustomervid", customeridMap, customervidMap);
			}
		}

		return list;
	}

	private void setSetValue(Set<String> oidSet, Set<String> vidSet, String oid, String vid) {
		if (!StringUtil.isSEmptyOrNull(oid)) {
			oidSet.add(oid);
		} else if (StringUtil.isSEmptyOrNull(oid) && !StringUtil.isSEmptyOrNull(vid)) {
			vidSet.add(vid);
		}

	}

	private void setVO(SuperVO vo, String oid, String vid, String oidParam, String vidParam,
			Map<String, String> oidToVidMap, Map<String, String> vidToOidMap) {
		if (!StringUtil.isSEmptyOrNull(oid)) {
			vo.setAttributeValue(vidParam, oidToVidMap.get(oid));
		} else if (StringUtil.isSEmptyOrNull(oid) && !StringUtil.isSEmptyOrNull(vid)) {
			vo.setAttributeValue(oidParam, vidToOidMap.get(vid));
		}

	}
}